package com.handong.handdemo.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.handong.handdemo.R;

import java.lang.reflect.Field;

/**
 * Created by userKey on 2017/6/29.
 */

public class RectangleInputLayout extends LinearLayout {

    private CharSequence mHintText;
    private int mLeftIconRes;
    private Drawable mShowPasswordIcon, mHidePasswordIcon;

    private ImageView mLeftIcon, mShowPassword;
    private EditText mInputEditText;
    private boolean mIsShowPassword = false;
    private boolean mPasswordShowing = false;

    public RectangleInputLayout(Context context) {
        super(context);
        initCustomView();
    }

    public RectangleInputLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttr(attrs, 0);
        initCustomView();
    }

    public RectangleInputLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttr(attrs, defStyleAttr);
        initCustomView();
    }

    private void initAttr(AttributeSet attr, int defAttr) {
        if (attr == null) {
            return;
        }

        TypedArray array = getContext().getTheme().obtainStyledAttributes(attr, R.styleable.RectangleInputLayout, defAttr, 0);
        try {
            mHintText = array.getString(R.styleable.RectangleInputLayout_ril_hintText);
            mLeftIconRes = array.getResourceId(R.styleable.RectangleInputLayout_ril_leftIcon, 0);
            mIsShowPassword = array.getBoolean(R.styleable.RectangleInputLayout_ril_showPassWordBtn, false);
        } finally {
            array.recycle();
        }
    }
    public static float displayMetricsDpi(Context context) {
        Context temp = context.getApplicationContext();
        DisplayMetrics metrics = temp.getResources().getDisplayMetrics();
        return metrics.density;
    }

    private void initCustomView() {
        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER_VERTICAL);
        setBackgroundColor(getContext().getResources().getColor(R.color.dialog_bg));

        float dpi = displayMetricsDpi(getContext());
        mLeftIcon = new ImageView(getContext());
        LayoutParams params = new LayoutParams(Math.round(28 * dpi), Math.round(28 * dpi));
        params.leftMargin = Math.round(20 * dpi);
        mLeftIcon.setLayoutParams(params);
        mLeftIcon.setImageResource(mLeftIconRes);
        addView(mLeftIcon);

        View view = new View(getContext());
        LayoutParams paramsLine = new LayoutParams(1, LayoutParams.MATCH_PARENT);
        paramsLine.leftMargin = Math.round(18 * dpi);
        //paramsLine.rightMargin = 10;
        paramsLine.topMargin = Math.round(8 * dpi);
        paramsLine.bottomMargin = Math.round(8 * dpi);
        view.setLayoutParams(paramsLine);
        view.setBackgroundColor(getResources().getColor(R.color.text_white));
        addView(view);

        mInputEditText = new EditText(getContext());
        LayoutParams paramsET = new LayoutParams(0, LayoutParams.WRAP_CONTENT);
        paramsET.weight = 8;
        mInputEditText.setLayoutParams(paramsET);
        mInputEditText.setHint(mHintText);
        mInputEditText.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
        mInputEditText.setTextSize(15f);
        mInputEditText.setPadding(Math.round(18 * dpi), 0, Math.round(18 * dpi), 0);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mInputEditText.setHintTextColor(this.getContext().getColor(R.color.text_white));
            mInputEditText.setTextColor(this.getContext().getColor(R.color.text_white));
        } else {
            mInputEditText.setHintTextColor(this.getContext().getResources().getColor(R.color.text_white));
            mInputEditText.setTextColor(this.getContext().getResources().getColor(R.color.text_white));
        }

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
            mInputEditText.setBackground(null);
        } else {
            mInputEditText.setBackgroundDrawable(null);
        }

        mInputEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!mIsShowPassword) {
                    return;
                }
                if (s.length() == 0) {
                    mShowPassword.setVisibility(GONE);
                    mPasswordShowing = false;
                } else {
                    if (mShowPassword.getVisibility() == GONE) {
                        mShowPassword.setVisibility(VISIBLE);
                        mPasswordShowing = true;
                    }
                }
            }
        });

        try {
            Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
            field.setAccessible(true);
            field.set(mInputEditText, R.drawable.edittext_cursor_drawable);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        addView(mInputEditText);

        if (mIsShowPassword) {
            mShowPassword = new ImageView(getContext());
            LayoutParams paramsBtn = new LayoutParams(Math.round(25 * dpi), Math.round(25 * dpi));
            paramsBtn.weight = 1;
            mShowPassword.setLayoutParams(paramsBtn);

            mShowPasswordIcon = ContextCompat.getDrawable(getContext(), R.drawable.svg_visibility_24dp_white).mutate();
            mHidePasswordIcon = ContextCompat.getDrawable(getContext(), R.drawable.svg_visibility_off_24dp_white).mutate();
            mShowPassword.setImageDrawable(mShowPasswordIcon);
            mInputEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());

            mShowPassword.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mPasswordShowing) {
                        mShowPassword.setImageDrawable(mShowPasswordIcon);
                        mInputEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                        mInputEditText.setSelection(mInputEditText.getText().length());
                    } else {
                        mShowPassword.setImageDrawable(mHidePasswordIcon);
                        mInputEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        mInputEditText.setSelection(mInputEditText.getText().length());
                    }
                    mPasswordShowing = !mPasswordShowing;
                }
            });
            mShowPassword.setVisibility(GONE);
            addView(mShowPassword);
        }
    }

    public void setInputContent(String content) {
        mInputEditText.setText(content);
        mInputEditText.setSelection(content.length());
    }

    public void requestEditTextFocus() {
        mInputEditText.requestFocus();
    }

    public String getInputContent() {
        return mInputEditText.getText().toString().trim();
    }

    public EditText getInputEditText() {
        return mInputEditText;
    }
}
